<?php

class html5av_manager_api {

    private static $param;

    static public function init() {
        self::$param = html5av_manager::getParam();
        if (!isset(self::$param['node'])) {
            exit();
        }
        if (method_exists(__CLASS__, 'cmd_' . self::$param['node'])) {
            call_user_func(array(__CLASS__, 'cmd_' . self::$param['node']));
        } else {
            echo 'Error command does not exist';
        }
        
        die();
    }

    static public function checkPermission($capability) {
        if (!current_user_can($capability)) {
            exit();
        }
    }

    static public function cmd_add_new_video() {
        self::checkPermission('edit_posts');
        $type = 'video';
        $title = self::$param['title'];
        $alt = self::$param['alt'];
        $tempPath = self::$param['path'];
        $poster_filename = self::$param['file'];
        $tempFile = $tempPath . '/' . $poster_filename;
        $poster_path = html5av_time::getUTC('Y') . '/' .
                html5av_time::getUTC('m') . '/' .
                html5av_manager::slug($title);
        $width = (int) self::$param['width'];
        $height = (int) self::$param['height'];
        $view = self::$param['view'];

        $video = new html5av_audio_video();

        $video->setCreatedOn();
        $video->setModified();
        $video->setAuthorId();
        $video->setPosterPath($poster_path);
        $video->setPosterFilename($poster_filename);
        $video->setTitle($title);
        $video->setAlt($alt);
        $video->setType($type);
        $video->setView($view);
        $video->setWidth($width);
        $video->setHeight($height);
        $video->save();

        @mkdir(html5av_manager::getUploadDir() . '/' . $video->getPosterPath(), 0755, true);
        rename($tempFile, $video->getPoster());

        echo $video->getID();
    }

    static public function cmd_add_new_audio() {
        self::checkPermission('edit_posts');
        $type = 'audio';
        $title = self::$param['title'];
        $alt = self::$param['alt'];
        $width = 0;
        $height = 0;
        $view = self::$param['view'];

        $audio = new html5av_audio_video();

        $audio->setCreatedOn();
        $audio->setModified();
        $audio->setAuthorId();
        $audio->setTitle($title);
        $audio->setAlt($alt);
        $audio->setType($type);
        $audio->setView($view);
        $audio->setWidth($width);
        $audio->setHeight($height);
        $audio->setPosterFilename('blank');
        $audio->setPosterPath('blank');
        $audio->save();

        echo $audio->getID();
    }

    static public function cmd_video_audio_manager_pagenation() {
        self::checkPermission('edit_posts');
        list($firstPage, $lastPage) = html5av_audio_video_table::pager();
        $currentPage = self::$param['page'];

        if ($lastPage <= 1) {
            echo '';
            return;
        }

        $pages = array();
        if ($currentPage != $firstPage)
            $pages['<<'] = $firstPage;
        if ($currentPage - 1 > 0)
            $pages['<'] = $currentPage - 1;
        if ($currentPage - 3 > 0)
            $pages[(string) $currentPage - 3] = $currentPage - 3;
        if ($currentPage - 2 > 0)
            $pages[(string) $currentPage - 2] = $currentPage - 2;
        if ($currentPage - 1 > 0)
            $pages[(string) $currentPage - 1] = $currentPage - 1;

        $pages[(string) $currentPage] = $currentPage;

        if ($currentPage + 1 <= $lastPage)
            $pages[(string) $currentPage + 1] = $currentPage + 1;
        if ($currentPage + 2 <= $lastPage)
            $pages[(string) $currentPage + 2] = $currentPage + 2;
        if ($currentPage + 3 <= $lastPage)
            $pages[(string) $currentPage + 3] = $currentPage + 3;
        if ($currentPage + 1 <= $lastPage)
            $pages['>'] = $currentPage + 1;
        if ($currentPage != $lastPage)
            $pages['>>'] = $lastPage;

        include 'view/admin/video-audio-manager-pagenation.php';
    }

    static public function cmd_video_audio_manager_page() {
        self::checkPermission('edit_posts');
        $page = (int) self::$param['page'];
        $tempVideoAudios = html5av_audio_video_table::getPage($page);

        if (!count($tempVideoAudios)) {
            include 'view/admin/no-av.php';
            return;
        }

        $AVs = array();
        foreach ($tempVideoAudios as $videoAudio) {
            if ($videoAudio->getType() != 'audio') {
                list($width, $height) = getimagesize($videoAudio->getPoster());

                $max = 50;
                $ratioW = $max / $width;
                $ratioH = $max / $height;
                $ratio = min($ratioW, $ratioH);

                $width = intval($ratio * $width);
                $height = intval($ratio * $height);
            } else {
                $width = 0;
                $height = 0;
            }

            $tempVideoAudio = array(
                'ID' => $videoAudio->getID(),
                'title' => htmlspecialchars($videoAudio->getTitle()),
                'alt' => htmlspecialchars($videoAudio->getAlt()),
                'type' => $videoAudio->getType(),
                'poster' => $videoAudio->getPosterUrl(),
                'author' => $videoAudio->getAuthorName(),
                'view' => $videoAudio->getView(),
                'created' => $videoAudio->getCreatedOn(),
                'modified' => $videoAudio->getModified(),
                'width' => $width,
                'height' => $height
            );

            $AVs[] = $tempVideoAudio;
        }

        include 'view/admin/video-audio-manager-page.php';
    }

    static public function cmd_video_audio_manager_delete() {
        self::checkPermission('edit_posts');
        $id = self::$param['avid'];
        $videoAudio = html5av_audio_video_table::getByID($id);
        $videoAudio->delete();
    }

    static public function cmd_get_media_editor() {
        self::checkPermission('edit_posts');
        html5av_manager::mediaEditor();
    }

    static public function cmd_video_edit_submit() {
        self::checkPermission('edit_posts');
        $id = self::$param['avid'];
        $video = html5av_audio_video_table::getByID($id);
        $title = self::$param['title'];
        $alt = self::$param['alt'];
        $width = (int) self::$param['width'];
        $height = (int) self::$param['height'];
        $view = self::$param['view'];

        $video->setModified();
        $video->setTitle($title);
        $video->setAlt($alt);
        $video->setWidth($width);
        $video->setHeight($height);
        $video->setView($view);
        $video->save();

        $video = html5av_audio_video_table::getByID($id);

        $array = array(
            'status' => 'Saved Succesfully',
            'title' => $video->getTitle(),
            'alt' => $video->getAlt(),
            'author' => $video->getAuthorName(),
            'created' => $video->getCreatedOn(),
            'modified' => $video->getModified()
        );

        echo json_encode($array);
    }

    static public function cmd_audio_edit_submit() {
        self::checkPermission('edit_posts');
        $id = self::$param['avid'];
        $audio = html5av_audio_video_table::getByID($id);
        $title = self::$param['title'];
        $alt = self::$param['alt'];
        $view = self::$param['view'];

        $audio->setModified();
        $audio->setTitle($title);
        $audio->setAlt($alt);
        $audio->setView($view);
        $audio->save();

        $audio = html5av_audio_video_table::getByID($id);

        $array = array(
            'status' => 'Saved Succesfully',
            'title' => $audio->getTitle(),
            'alt' => $audio->getAlt(),
            'author' => $audio->getAuthorName(),
            'created' => $audio->getCreatedOn(),
            'modified' => $audio->getModified()
        );

        echo json_encode($array);
    }

    static public function cmd_source_upload() {
        self::checkPermission('edit_posts');
        $id = self::$param['avid'];
        $videoAudio = html5av_audio_video_table::getByID($id);
        $type = trim($videoAudio->getType());
        if ($type == 'video') {
            $fileDesc = 'HTML5 Video Files';
            $buttonText = 'Select Video Files';
            $fileType = implode(';', html5av_manager::getVideoExt());
        } else {
            $fileDesc = 'HTML5 Audio Files';
            $buttonText = 'Select Audio Files';
            $fileType = implode(';', html5av_manager::getAudioExt());
        }
        include 'view/admin/source-panel.php';
    }

    static public function cmd_source_upload_submit() {
        self::checkPermission('edit_posts');
        $id = self::$param['avid'];
        $videoAudio = html5av_audio_video_table::getByID($id);
        $title = $videoAudio->getTitle();
        $count = self::$param['count'];
        $tempPath = self::$param['path'];
        $path = html5av_time::getUTC('Y') . '/' .
                html5av_time::getUTC('m') . '/' .
                html5av_manager::slug($title);
        $file = self::$param['file'];
        $tempFile = $tempPath . '/' . $file;
        $type = html5av_manager::determineType($file, $videoAudio->getType());

        $source = new html5av_source();

        $source->setAudioVideoId($videoAudio->getID());
        $source->setDisabled(false);
        $source->setExternalMode(false);
        $source->setExternalUrl('');
        $source->setUploadFilename($file);
        $source->setUploadPath($path);
        $source->setOrderNo($count);
        $source->setType($type);
        $source->save();

        @mkdir(html5av_manager::getUploadDir() . '/' . $source->getUploadPath(), 0755, true);
        rename($tempFile, $source->getSrc());
    }

    static public function cmd_source_external() {
        $id = self::$param['avid'];
        $videoAudio = html5av_audio_video_table::getByID($id);
        $type = trim($videoAudio->getType());
        if ($type == 'video') {
            $codecTypes = html5av_manager::getVideoType();
        } else {
            $codecTypes = html5av_manager::getAudioType();
        }

        include 'view/admin/source-external-panel.php';
    }

    static public function cmd_source_external_submit() {
        self::checkPermission('edit_posts');
        $id = self::$param['avid'];
        $videoAudio = html5av_audio_video_table::getByID($id);
        $count = (int) count($videoAudio->getSources(true)) + 1;
        $type = self::$param['type'];
        $url = self::$param['url'];

        $source = new html5av_source();

        $source->setAudioVideoId($videoAudio->getID());
        $source->setDisabled(false);
        $source->setExternalMode(true);
        $source->setExternalUrl($url);
        $source->setUploadFilename('');
        $source->setUploadPath('');
        $source->setOrderNo($count);
        $source->setType($type);
        $source->save();
    }

    static public function cmd_track_upload() {
        self::checkPermission('edit_posts');
        include 'view/admin/track-panel.php';
    }

    static public function cmd_track_upload_submit() {
        self::checkPermission('edit_posts');
        $id = self::$param['avid'];
        $videoAudio = html5av_audio_video_table::getByID($id);
        $title = $videoAudio->getTitle();
        $count = self::$param['count'];
        $tempPath = self::$param['path'];
        $path = html5av_time::getUTC('Y') . '/' .
                html5av_time::getUTC('m') . '/' .
                html5av_manager::slug($title);
        $file = self::$param['file'];
        $tempFile = $tempPath . '/' . $file;
        $kind = 'subtitles';
        $srclang = 'en';
        $label = 'English';

        $track = new html5av_track();

        $track->setAudioVideoId($videoAudio->getID());
        $track->setOrderNo($count);
        $track->setDisabled(false);
        $track->setExternalMode(false);
        $track->setExternalUrl('');
        $track->setUploadPath($path);
        $track->setUploadFilename($file);
        $track->setKind($kind);
        $track->setSrclang($srclang);
        $track->setLabel($label);
        $track->save();

        @mkdir(html5av_manager::getUploadDir() . '/' . $track->getUploadPath(), 0755, true);
        rename($tempFile, $track->getSrc());
    }

    static public function cmd_track_external() {
        self::checkPermission('edit_posts');

        $kinds = html5av_manager::getTrackKinds();

        include 'view/admin/track-external-panel.php';
    }

    static public function cmd_track_external_submit() {
        self::checkPermission('edit_posts');
        $id = self::$param['avid'];
        $videoAudio = html5av_audio_video_table::getByID($id);
        $title = $videoAudio->getTitle();
        $count = (int) count($videoAudio->getTracks(true)) + 1;
        $kind = trim(self::$param['kind']);
        $srclang = trim(self::$param['srclang']);
        $label = trim(self::$param['label']);
        $src = trim(self::$param['src']);

        $track = new html5av_track();

        $track->setAudioVideoId($videoAudio->getID());
        $track->setOrderNo($count);
        $track->setDisabled(false);
        $track->setExternalMode(true);
        $track->setExternalUrl($src);
        $track->setUploadPath('');
        $track->setUploadFilename('');
        $track->setKind($kind);
        $track->setSrclang($srclang);
        $track->setLabel($label);
        $track->save();
    }

    static public function cmd_source_count() {
        self::checkPermission('edit_posts');
        $id = self::$param['avid'];
        $videoAudio = html5av_audio_video_table::getByID($id);
        $count = (int) count($videoAudio->getSources(true));
        $array = array(
            'count' => $count
        );
        echo json_encode($array);
    }

    static public function cmd_track_count() {
        self::checkPermission('edit_posts');
        $id = self::$param['avid'];
        $videoAudio = html5av_audio_video_table::getByID($id);
        $count = (int) count($videoAudio->getTracks(true));
        $array = array(
            'count' => $count
        );
        echo json_encode($array);
    }

    static public function cmd_update_source() {
        self::checkPermission('edit_posts');
        $id = self::$param['srcid'];
        $type = self::$param['type'];
        $disabled = trim(self::$param['disabled']);
        if ($disabled == 'true') {
            $disabled = true;
        } else {
            $disabled = false;
        }

        $source = html5av_source_table::getByID($id);
        $source->setType($type);
        $source->setDisabled($disabled);
        $source->save();

        echo 'Saved';
    }

    static public function cmd_reorder_source() {
        self::checkPermission('edit_posts');
        $tempOrder = self::$param['order'];
        $tempOrder = explode('&', $tempOrder);
        $orders = array();
        foreach ($tempOrder as $str) {
            $orders[] = (int) str_replace('source-id[]=', '', $str);
        }
        $count = 0;
        foreach ($orders as $order) {
            $count++;
            $source = html5av_source_table::getByID($order);
            $source->setOrderNo($count);
            $source->save();
        }
    }

    static public function cmd_update_track() {
        self::checkPermission('edit_posts');
        $id = self::$param['trackid'];
        $kind = self::$param['kind'];
        $disabled = trim(self::$param['disabled']);
        $srclang = trim(self::$param['srclang']);
        $label = trim(self::$param['label']);
        if ($disabled == 'true') {
            $disabled = true;
        } else {
            $disabled = false;
        }

        $track = html5av_track_table::getByID($id);
        $track->setKind($kind);
        $track->setDisabled($disabled);
        $track->setSrclang($srclang);
        $track->setLabel($label);
        $track->save();

        echo 'Saved';
    }

    static public function cmd_reorder_track() {
        self::checkPermission('edit_posts');
        $tempOrder = self::$param['order'];
        $tempOrder = explode('&', $tempOrder);
        $orders = array();
        foreach ($tempOrder as $str) {
            $orders[] = (int) str_replace('track-id[]=', '', $str);
        }
        $count = 0;
        foreach ($orders as $order) {
            $count++;
            $track = html5av_track_table::getByID($order);
            $track->setOrderNo($count);
            $track->save();
        }
    }

    static public function cmd_delete_source() {
        self::checkPermission('edit_posts');
        $id = self::$param['srcid'];
        $source = html5av_source_table::getByID($id);
        $source->delete();
    }

    static public function cmd_delete_track() {
        self::checkPermission('edit_posts');
        $id = self::$param['trackid'];
        $track = html5av_track_table::getByID($id);
        $track->delete();
    }

    static public function cmd_get_av_info() {
        self::checkPermission('edit_posts');
        $id = self::$param['avid'];
        $audioVideo = html5av_audio_video_table::getByID($id);

        $array = array(
            'type' => $audioVideo->getType(),
            'title' => $audioVideo->getTitle(),
            'created' => $audioVideo->getCreatedOn(),
            'modified' => $audioVideo->getModified()
        );
        echo json_encode($array);
    }

    static public function cmd_select_av() {
        self::checkPermission('edit_posts');
        html5av_manager::videoAudioManagerPanel();
    }

    static public function cmd_add_video() {
        self::checkPermission('edit_posts');
        html5av_manager::videoAddPanel();
    }

    static public function cmd_add_audio() {
        self::checkPermission('edit_posts');
        html5av_manager::audioAddPanel();
    }

    static public function cmd_setting_file_submit() {
        self::checkPermission('edit_posts');
        $setting_location = html5av_manager::getViewPath() . '/setting.php';
        $data = self::$param['setting_file'];
        file_put_contents($setting_location, $data);
        echo "Success!";
    }

    static public function cmd_get_view_file() {
        self::checkPermission('edit_posts');
        $file = html5av_manager::getViewPath() . '/'
                . self::$param['current_file'];
        $data = @file_get_contents($file);
        $filename = self::$param['current_file'];
        $json = array(
            'data' => $data,
            'filename' => $filename
        );
        echo json_encode($json);
    }

    static public function cmd_get_view_filelist() {
        self::checkPermission('edit_posts');
        $current_file = self::$param['current_file'];
        $filelist = array();

        $viewsDir = html5av_manager::getViewPath() . '/';

        $audioViews = glob($viewsDir . "audio-*.php");

        foreach ($audioViews as $view) {
            $view = basename($view);
            $filelist[] = $view;
        }

        $videoViews = glob($viewsDir . "video-*.php");

        foreach ($videoViews as $view) {
            $view = basename($view);
            $filelist[] = $view;
        }

        include 'view/admin/view-editor-filelist.php';
    }

    static public function cmd_view_file_submit() {
        self::checkPermission('edit_posts');
        $current_file = html5av_manager::getViewPath() . '/' .
                self::$param['current_file'];
        $data = self::$param['data'];
        file_put_contents($current_file, $data);
        echo 'Success!';
    }

    static public function cmd_new_view_submit() {
        self::checkPermission('edit_posts');
        $proposed_file = html5av_manager::getViewPath() . '/' .
                self::$param['mediatype'] . '-' .
                self::$param['title'] . '.php';
        if (file_exists($proposed_file)) {
            echo "File Already Exist!";
            return;
        } else {
            $dir = html5av_manager::getDir();
            copy($dir . '/view/videoaudio/' . self::$param['mediatype']
                    . '-default.php', $proposed_file);
            echo "Success! (If allowed by server Operating System)";
        }
    }

}

add_action('wp_ajax_html5av_manager', array('html5av_manager_api', 'init'));
add_action('wp_ajax_nopriv_html5av_manager', array('html5av_manager_api', 'init'));
